import type { IRouteInfoResp } from '@/api/types'
import { computed, ref } from 'vue'
import { getRouteApi } from '@/api/auth/route'

/**
 * 路由状态管理
 */
export interface RouteState {
  /** 路由列表 */
  routes: IRouteInfoResp[]
  /** 加载状态 */
  loading: boolean
  /** 错误信息 */
  error: string | null
}

/**
 * 路由处理选项
 */
export interface UseRouteOptions {
  /** 是否立即加载 */
  immediate?: boolean
  /** 过滤函数 */
  filter?: (route: IRouteInfoResp) => boolean
  /** 排序函数 */
  sort?: (a: IRouteInfoResp, b: IRouteInfoResp) => number
}

/**
 * 路由工具类
 */
export class RouteUtils {
  /**
   * 过滤可见路由
   */
  static filterVisibleRoutes(routes: IRouteInfoResp[]): IRouteInfoResp[] {
    return routes.filter(route => !route.isHidden)
  }

  /**
   * 过滤菜单类型路由
   */
  static filterMenuRoutes(routes: IRouteInfoResp[]): IRouteInfoResp[] {
    return routes.filter(route => route.type === 1)
  }

  /**
   * 过滤目录类型路由
   */
  static filterDirectoryRoutes(routes: IRouteInfoResp[]): IRouteInfoResp[] {
    return routes.filter(route => route.type === 0)
  }

  /**
   * 按排序值排序
   */
  static sortByOrder(routes: IRouteInfoResp[]): IRouteInfoResp[] {
    return [...routes].sort((a, b) => a.sort - b.sort)
  }

  /**
   * 扁平化路由树
   */
  static flattenRoutes(routes: IRouteInfoResp[]): IRouteInfoResp[] {
    const result: IRouteInfoResp[] = []

    function traverse(routes: IRouteInfoResp[]) {
      routes.forEach((route) => {
        result.push(route)
        if (route.children?.length) {
          traverse(route.children)
        }
      })
    }

    traverse(routes)
    return result
  }

  /**
   * 查找路由
   */
  static findRoute(routes: IRouteInfoResp[], predicate: (route: IRouteInfoResp) => boolean): IRouteInfoResp | null {
    function search(routes: IRouteInfoResp[]): IRouteInfoResp | null {
      for (const route of routes) {
        if (predicate(route)) {
          return route
        }
        if (route.children?.length) {
          const found = search(route.children)
          if (found)
            return found
        }
      }
      return null
    }

    return search(routes)
  }

  /**
   * 根据路径查找路由
   */
  static findRouteByPath(routes: IRouteInfoResp[], path: string): IRouteInfoResp | null {
    return this.findRoute(routes, route => route.path === path)
  }

  /**
   * 根据名称查找路由
   */
  static findRouteByName(routes: IRouteInfoResp[], name: string): IRouteInfoResp | null {
    return this.findRoute(routes, route => route.name === name)
  }

  /**
   * 获取面包屑路径
   */
  static getBreadcrumb(routes: IRouteInfoResp[], targetRoute: IRouteInfoResp): IRouteInfoResp[] {
    const breadcrumb: IRouteInfoResp[] = []

    function findPath(routes: IRouteInfoResp[], target: IRouteInfoResp, path: IRouteInfoResp[]): boolean {
      for (const route of routes) {
        const currentPath = [...path, route]
        if (route.id === target.id) {
          breadcrumb.push(...currentPath)
          return true
        }
        if (route.children?.length && findPath(route.children, target, currentPath)) {
          return true
        }
      }
      return false
    }

    findPath(routes, targetRoute, [])
    return breadcrumb
  }
}

/**
 * 路由管理 Hook
 */
export function useRoute(options: UseRouteOptions = {}) {
  const { immediate = true, filter, sort } = options

  // 状态
  const routes = ref<IRouteInfoResp[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const visibleRoutes = computed(() => RouteUtils.filterVisibleRoutes(routes.value))
  const menuRoutes = computed(() => RouteUtils.filterMenuRoutes(visibleRoutes.value))
  const directoryRoutes = computed(() => RouteUtils.filterDirectoryRoutes(visibleRoutes.value))
  const sortedRoutes = computed(() => RouteUtils.sortByOrder(visibleRoutes.value))
  const flattenedRoutes = computed(() => RouteUtils.flattenRoutes(routes.value))

  /**
   * 加载路由数据
   */
  const loadRoutes = async () => {
    loading.value = true
    error.value = null

    try {
      const response = await getRouteApi()

      // 处理后端返回的数据结构
      let routeData: IRouteInfoResp[] = []

      if (response && typeof response === 'object') {
        // 如果response直接是数组
        if (Array.isArray(response)) {
          routeData = response
        }
        // 如果response有data字段且data是数组
        else if ((response as any).data && Array.isArray((response as any).data)) {
          routeData = (response as any).data
        }
        // 如果response本身就是路由数据对象
        else if (response.id && response.title) {
          routeData = [response as IRouteInfoResp]
        }
      }

      // 应用自定义过滤
      if (filter) {
        routeData = routeData.filter(filter)
      }

      // 应用自定义排序
      if (sort) {
        routeData = [...routeData].sort(sort)
      }

      routes.value = routeData
      return routeData
    }
    catch (err) {
      error.value = err instanceof Error ? err.message : '加载路由失败'
      console.error('加载路由失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 重新加载路由
   */
  const reload = async () => {
    return await loadRoutes()
  }

  /**
   * 查找路由
   */
  const findRoute = (predicate: (route: IRouteInfoResp) => boolean) => {
    return RouteUtils.findRoute(routes.value, predicate)
  }

  /**
   * 根据路径查找路由
   */
  const findRouteByPath = (path: string) => {
    return RouteUtils.findRouteByPath(routes.value, path)
  }

  /**
   * 根据名称查找路由
   */
  const findRouteByName = (name: string) => {
    return RouteUtils.findRouteByName(routes.value, name)
  }

  /**
   * 获取面包屑路径
   */
  const getBreadcrumb = (targetRoute: IRouteInfoResp) => {
    return RouteUtils.getBreadcrumb(routes.value, targetRoute)
  }

  /**
   * 检查是否有权限
   */
  const hasPermission = (permission: string) => {
    return !!RouteUtils.findRoute(routes.value, route => route.permission === permission)
  }

  // 立即加载
  if (immediate) {
    loadRoutes()
  }

  return {
    // 状态
    routes,
    loading,
    error,

    // 计算属性
    visibleRoutes,
    menuRoutes,
    directoryRoutes,
    sortedRoutes,
    flattenedRoutes,

    // 方法
    loadRoutes,
    reload,
    findRoute,
    findRouteByPath,
    findRouteByName,
    getBreadcrumb,
    hasPermission,

    // 工具类
    RouteUtils,
  }
}

/**
 * 简化版路由 Hook - 只返回处理后的路由数据
 */
export function useSimpleRoute(options: UseRouteOptions = {}) {
  const {
    routes,
    loading,
    error,
    visibleRoutes,
    menuRoutes,
    reload,
  } = useRoute(options)

  return {
    routes,
    loading,
    error,
    visibleRoutes,
    menuRoutes,
    reload,
  }
}
